<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">{{ page.total + "条记录" }}</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=employee')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像">
            <template slot-scope="{row}">
              <img v-imageError="require('@/assets/common/bigUserHeader.png')" class="avatar" :src="row.staffPhoto" alt="" @click="showPopup(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" prop="username" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="page.total" @current-change="currentChange" />
        </el-row>
      </el-card>
      <!-- 新增用户弹窗 -->
      <AddEmployee :show-dialog.sync="showDialog" @addEmployee="addEmployee" />

      <!-- 二维码弹窗 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog" @opened="showQRcode">
        <el-row type="flex" justify="center">
          <canvas v-if="showCodeDialog" ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { delEmployee, getEmployeeList } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from '@/views/employees/components/add-employee.vue'
import { formatDate } from '@/filters'
// 转换二维码的工具
import QRcode from 'qrcode'
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      // 新增员工弹窗数据
      showDialog: false,

      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      // 二维码弹窗数据
      showCodeDialog: false,
      avatarImg: '' // 储存图片地址
    }
  },
  mounted() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工的综合列表数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      // console.log(this.list)
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 在饿了么中 查看 el-table-column的formatter属性进行设置
    formatEmployment(row, column, cellValue, index) {
      // return cellValue === 1 ? '正式员工' : '临时员工'
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      // console.log(obj)
      return obj ? obj.value : '未知'
    },

    // 新增员工的自定义事件
    addEmployee() {
      this.getEmployeeList()
      this.showDialog = false
    },

    // 员工操作 ：删除
    async delEmployee(id) {
      await this.$confirm('您确定删除该员工吗')
      await delEmployee(id)
      // 补充, 如果当前页面只剩下一条数据, 而且当前页码并非第一页
      // 就要删除后往前翻页
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page -= 1
      }
      await this.getEmployeeList()
      this.$message.success('操作成功')
    },
    // 点击导出按钮 下载数据
    async exportData() {
      // 获取数据
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      // 表头对应关系
      // header / data这两个都可以利用字典进行生成
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      // 拿到所有中文的表头
      const header = Object.keys(dict)
      // 接着准备 data 也就是员工数组
      const data = rows.map(user => {
        // 这里每个接到的都是 user 对象
        // 需要转成数组, 可以封装函数, 传入员工对象和字典
        // 需要返回一个合格的员工数组
        return this.objToArray(user, dict)
      })
      // 懒加载
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header,
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'

        })
      })
    },
    objToArray(userObj, dict) {
      const header = Object.keys(dict)
      const userArr = []
      header.forEach(cnkey => {
        const enkey = dict[cnkey]
        let value = userObj[enkey]
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          value = new Date(formatDate(value))
        }
        if (enkey === 'formOfEmployment') {
          const obj = EmployeeEnum.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知'
        }
        userArr.push(value)
      })
      return userArr
    },
    // 点击头像生成二维码
    showPopup(imageUrl) {
      if (imageUrl) {
        // 1. 将头像地址记录
        this.avatarImg = imageUrl
        // 2. 弹窗
        this.showCodeDialog = true
      }
    },
    showQRcode() {
      QRcode.toCanvas(this.$refs.myCanvas, this.avatarImg)
    }
  }
}
</script>
.<style lang="scss" scoped>
.avatar{
  width:100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}
</style>
